package com.gyyweishang.interceptor;

import com.gyyweishang.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 令牌校验拦截器
 */
@Slf4j
@Component//@Component注解用于定义一个Bean
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//        //获取请求路径
//        String path = request.getRequestURI();
//        //判断是否是登录请求，如果是，放行;路径中包含/login的都放行
//        if (path.contains("/login")) {
//            log.info("登录请求，放行");
//            return true;
//        }

        //获取请求头中的令牌 token
        String token = request.getHeader("token");
        //判断令牌是否为空
        if (token == null || token.isEmpty()) {
            log.info("令牌为空，响应401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //验证令牌是否正确
        try {
            JwtUtils.parseToken(token); //解析令牌
        } catch (Exception e) {
            log.info("令牌错误，响应401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //放行
        log.info("令牌正确，放行");
        return  true;
    }
}
